package com.hl.toolkit.server.bdpay;

import com.alibaba.fastjson.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;


public class BfbSdkComm {
	/**
	 * 生成百度钱包接口对应的URL
	 *
	 * @param array $params	生成订单的参数数组，具体参数的取值参见接口文�?
	 * @param string $url   百度钱包URL
	 * @return string 返回生成的百度钱包接口URL
	 * @throws UnsupportedEncodingException  
	 */
	public String   create_bdpay_pay_order_url(String[] ary,String[] ary1 ,String url) throws UnsupportedEncodingException
	{
		//首先判断传入的必选参数是否为?
		//调用make_sign方法，返回签名结果sign，给参数排序和签名? 
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ary1.length; i++) {
			// 属性的值是否为�?,值为空的参数名参与拼接，其他正常拼接
			ary1[i].substring(ary1[i].indexOf("=") + 1, ary1[i].length());

			sb.append(ary1[i] + "&");

		} 
		String newStr =sb.toString(); 
        String sign=make_sign(ary);
        //�? URL get串提交串参数 
        //提交
        
        
        String urlGet=url+"?"+newStr+"sign="+sign;
		return  urlGet;
	}
	
	public String create_baifubao_pay_order_url(String[] ary, String[] ary1,
			String url) throws UnsupportedEncodingException {
		// 首先判断传入的必选参数是否为空
		// 调用make_sign方法，返回签名结果sign，给参数排序和签名
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ary1.length; i++) {
			// 属性的值是否为空,值为空的参数名参与拼接，其他正常拼接
			ary1[i].substring(ary1[i].indexOf("=") + 1, ary1[i].length());

			sb.append(ary1[i] + "&");

		}
		String newStr = sb.toString();
		String sign = make_sign(ary);
		// 组 URL get串提交串参数
		// 提交
		String urlGet = url + "?" + newStr + "sign=" + sign;
		return urlGet;
	}

	/**
	 * 计算数组的签名，传入参数为数组，算法如下�?
	 * 1.
	 * 对数组按KEY进行升序排序
	 * 2. 在排序后的数组中添加商户密钥，键名为key，键值为商户密钥
	 * 3. 将数组拼接成字符串，以key=value&key=value的形式进行拼接，注意这里不能直接调用
	 * http_build_query方法，因为该方法会对参数进行URL编码
	 * 4. 要所传入数组中的$params ['sign_method']定义的加密算法，对拼接好的字符串进行加密，生成的便是签名�?
	 * $params ['sign_method']等于1使用md5加密，等�?2使用sha-1加密
	 *
	 * @param array $params 生成签名的数�?
	 * @return string | boolean 成功返回生成签名，失败返回false
	 */
	public String   make_sign(String[] ary)
	{
		Arrays.sort(ary,String.CASE_INSENSITIVE_ORDER);   
		//对参数数组进行按key升序排列,然后拼接，最后调�?5签名方法
		StringBuffer sb = new StringBuffer();
		for(int i = 0; i < ary.length; i++)
		{  
				sb. append(ary[i]+"&");	
		}
		String newStrTemp = sb.toString()+"key="+GetKey().trim();
		//获取sign_method
		String signmethod= GetMethodSign(newStrTemp);
		//根据sign_method选择使用MD5签名1，还是哈希签�?2
		String sign=null;
		if(signmethod.equals("1")){
		  sign =new MD5().md5Digest(newStrTemp); 
		}
		else if(signmethod.equals("2")){
	      sign =new SHA1().Digest(newStrTemp,"gbk").toLowerCase();
		}
		System.out.println("str待签名串: " + newStrTemp + ";签名? sign=" + sign);
		return sign;
	}
	public Logger  printLog(String strName)
	{
		Logger logger = Logger. getLogger(strName);
		FileHandler fileHandler = null;
		try {
		       fileHandler = new FileHandler("D:/bdlog/bdpayLog.txt", 0, 1, true);//
		       //参数1：指定日志输出文件路? 参数2：表示文件最大字节数 0表示不限?
		       // 参数3：日志文件数可以多个 参数4：是否在原来日志后追加日�?,true表示追加日志文件而不是重新修�?
		} catch (Exception ex) {
		       ex.printStackTrace();
		}
		fileHandler.setLevel(Level.FINER);//设置日志文件中输出级�?
		fileHandler.setFormatter(new SimpleFormatter());//设置输出信息格式为普通格? 默认为XML?
		logger.addHandler(fileHandler);
		logger.setLevel(Level.FINER);//设置日志级别
		return logger;
	}
	private  String GetKey(){  
 	        return BaiduConfig.key;  
    }  
	private String GetMethodSign(String  sb){	
		int aa=sb.indexOf("sign_method=");
	    String signmethod= sb.substring(aa+12,aa+13);
		return signmethod;
	}
	
	public String verify_sign(JSONObject json) {
		JSONObject data=json.getJSONObject("content");
		String[] ary = { "order_no=" + data.getString("order_no"),
				"qrcode=" + data.getString("qrcode"),
				"sign_method=" + data.getString("sign_method"),
				"sp_no=" + data.getString("sp_no"),
				"version=" + data.getString("version"),};

		Arrays.sort(ary, String.CASE_INSENSITIVE_ORDER);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ary.length; i++) {
			sb.append(ary[i] + "&");
		}
		String newStrTemp = sb.toString() + "key=" + GetKey().trim();
		String sign = null;
		sign = new MD5().md5Digest(newStrTemp);
		return sign;
	}
	public String verify_CodePay_sign(JSONObject json) {
		JSONObject data=json.getJSONObject("content");
		String[] ary = { "bfb_order_no=" + data.getString("bfb_order_no"),
				"order_no=" + data.getString("order_no"),
				"pay_result=" + data.getString("pay_result"),
				"sign_method=" + data.getString("sign_method"),
				"version=" + data.getString("version"),
				"sp_no=" + data.getString("sp_no"),};

		Arrays.sort(ary, String.CASE_INSENSITIVE_ORDER);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ary.length; i++) {
			sb.append(ary[i] + "&");
		}
		String newStrTemp = sb.toString() + "key=" + GetKey().trim();
		String sign = null;
		System.out.println(newStrTemp);
		sign = new MD5().md5Digest(newStrTemp);
		return sign;
	}
	public String verify_apireverse_sign(JSONObject json) {
		JSONObject data=json.getJSONObject("content");
		String[] ary = { "bfb_order_no=" + data.getString("bfb_order_no"),
				"order_no=" + data.getString("order_no"),
				"reverse_result=" + data.getString("reverse_result"),
				"reverse_time=" + data.getString("reverse_time"),
				"version=" + data.getString("version"),
				"sign_method=" + data.getString("sign_method"),
				"sp_no=" + data.getString("sp_no"),};

		Arrays.sort(ary, String.CASE_INSENSITIVE_ORDER);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ary.length; i++) {
			sb.append(ary[i] + "&");
		}
		String newStrTemp = sb.toString() + "key=" + GetKey().trim();
		String sign = null;
		sign = new MD5().md5Digest(newStrTemp);
		System.out.println(newStrTemp);
		return sign;
	}
	
	public String verify_query_sign(JSONObject json) {
		JSONObject data=json.getJSONObject("content");
		String[] ary = { "bfb_order_no=" + data.getString("bfb_order_no"),
				"cash_amount=" + data.getString("cash_amount"),
				"create_time=" + data.getString("create_time"),
				"goods_name=" + data.getString("goods_name"),
				"mkt_amount=" + data.getString("mkt_amount"),
				"mname=" + data.getString("mname"),
				"mno=" + data.getString("mno"),
				"order_no=" + data.getString("order_no"),
				"pay_result=" + data.getString("pay_result"),
				"pay_time=" + data.getString("pay_time"),
				"sign_method=" + data.getString("sign_method"),
				"sp_no=" + data.getString("sp_no"),
				"tno=" + data.getString("tno"),
				"total_amount=" + data.getString("total_amount"),
				"version=" + data.getString("version"),};

		Arrays.sort(ary, String.CASE_INSENSITIVE_ORDER);
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < ary.length; i++) {
			sb.append(ary[i] + "&");
		}
		String newStrTemp = sb.toString() + "key=" + GetKey().trim();
		String sign = null;
		sign = new MD5().md5Digest(newStrTemp);
		System.out.println(newStrTemp);
		return sign;
	}
	
   
}
